package com.key.tools;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.apache.tomcat.jdbc.pool.DataSource;
import org.apache.tomcat.jdbc.pool.PoolProperties;

public class ConnectionPool {

	public static String dburl = "jdbc:mysql://115.28.1.240:3306/public_monitor?characterEncoding=utf8";
	public static String classname = "com.mysql.jdbc.Driver";
	public static String username = "root";
	public static String password = "szl";
	
	private PoolProperties properties = null;
	private DataSource datasource = null;
	
	private static ConnectionPool pool = null;
	
	private ConnectionPool(){
		
	}
	
	public static ConnectionPool getInstance() {
		if(pool == null) {
			synchronized(ConnectionPool.class) {
				if(pool == null) {
					pool = new ConnectionPool();
					pool.init();
				}
			}
		}
		return pool;
	}
	
	public void init() {
		if(properties == null) {
			synchronized(ConnectionPool.class) {
				if(properties == null) {
					properties = new PoolProperties();
					properties.setUrl(dburl);
					properties.setDriverClassName(classname);
					properties.setUsername(username);
					properties.setPassword(password);
					properties.setJmxEnabled(true);
					properties.setTestWhileIdle(false);
					properties.setTestOnBorrow(true);
					properties.setValidationQuery("SELECT 1");
					properties.setTestOnReturn(false);
					properties.setValidationInterval(30000);
					properties.setTimeBetweenEvictionRunsMillis(30000);
					properties.setMaxActive(100);
					properties.setInitialSize(10);
					properties.setMaxWait(10000);
					properties.setRemoveAbandonedTimeout(60);
					properties.setMinEvictableIdleTimeMillis(30000);
					properties.setMinIdle(10);
					properties.setLogAbandoned(true);
					properties.setRemoveAbandoned(true);
					properties.setJdbcInterceptors("org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;"
							+ "org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer");
					datasource = new DataSource();
					datasource.setPoolProperties(properties);
				}
			}
		}
	}
	
	public Connection getConnection() {
		try {
			return datasource.getConnection();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}
	
//  example
//	Connection con = ConnectionPool.getInstance().getConnection();
//	try {
//	  Statement st = con.createStatement();
//	  ResultSet rs = st.executeQuery("select * from t_admin_user");
//	  int cnt = 1;
//	  while (rs.next()) {
//	      System.out.println((cnt++)+
//		" User:"+rs.getString("username")+" Password:"+rs.getString("password"));
//	  }
//	  rs.close();
//	  st.close();
//	} finally {
//	  if (con!=null) try {con.close();}catch (Exception ignore) {}
//	}
}
